<?php

$st = microtime(true);
define('BASE_DIR', dirname(__FILE__));
ignore_user_abort(true);

include 'config/server.php';
include 'lib/autoload.php';
include 'lib/utils.php';
include 'lib/db.php';
include 'lib/controller.php';
include 'lib/view.php';
include 'lib/exceptions.php';
include 'lib/smarty/Smarty.class.php';

try
{
	Service_Startup::loadConfig();
	Service_Startup::connectDatabase();
	// extravert
	//Service_Startup::sendHeaders();
	Service_Startup::startSession();
	
	list($controllerClass, $event, $params) = Service_Startup::parseUrl();
    $user = getCurrentUser();
	if (!$user && ($controllerClass != 'Controller_Main' || $event != 'login'))
	{
		Redirect('/login');
	}

    if ($user && $controllerClass == 'Controller_Main' && $event == 'home')
    {
        Redirect('/'.$user['utype']);
    }
	
	if (!$controllerClass)
	{
	    throw new ExceptionNotFound();
	}
	$controller = new $controllerClass();
	$response = $controller->run($event, $params);
}
catch (ExceptionNotFound $ex)
{
	$response = Controller_Error::notFound($ex->title, $ex->comment);
}
catch (ExceptionForbidden $ex)
{
	$response = Controller_Error::forbidden($ex->title, $ex->comment);
}
catch (ExceptionNotAvailable $ex)
{
	$response = Controller_Error::notAvailable();
}
catch (Exception $ex)
{
	$response = Controller_Error::internalError('Внутренняя ошибка', $ex->getMessage());
}

Profiler::finish();

echo $response;
exit;